
package ru.surfstudio.webservicetemplate;

import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import ru.surfstudio.webservicetemplate.service.RestExecutor;
import ru.surfstudio.webservicetemplate.util.HttpClientInitializer;
import android.app.Application;

public class WSApplication extends Application {

	private RestExecutor restExecutor;

    private HttpComponentsClientHttpRequestFactory clientHttpRequestFactory;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        shutdownHttpClient();
    }

    public RestExecutor getRestExecutor() {
        if (restExecutor == null) {
            restExecutor = new RestExecutor(getClientHttpRequestFactory());
        }
        return restExecutor;
    }

    public ClientHttpRequestFactory getClientHttpRequestFactory() {
		if (clientHttpRequestFactory == null) {
			DefaultHttpClient httpClient = HttpClientInitializer.getHttpClient(this);
			// We don't need persistent cookie storage in the project, but often it could be useful 
			// httpClient.setCookieStore(new PersistentCookieStore(this));
			clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
			clientHttpRequestFactory.setHttpClient(httpClient);
			int requestTimeout = getResources().getInteger(R.integer.request_timeout);
			clientHttpRequestFactory.setReadTimeout(requestTimeout);
		}
        return clientHttpRequestFactory;
    }

    private void shutdownHttpClient() {
        if (clientHttpRequestFactory != null) {
            clientHttpRequestFactory.destroy();
        }
    }
}